package wpp.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.platform.win32.WinDef.UINT_PTR;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIFunctionMapper;
import com.sun.jna.win32.W32APITypeMapper;

import wpp.exception.WPPException;

public abstract class OSUtil {
	
	private static OSUtil instance;
		
	static {
		if(Platform.isWindows()) {
			instance = new WindowsUtil();
		} else if(Platform.isLinux()) {
			instance = new LinuxGNOMEUtil();
		}
	}
	
	public static OSUtil getInstance() {
		return instance;
	}
	
	public abstract File getUserHomeDirectory();
	public abstract void changeWallpaper(String path);
	
	private static class WindowsUtil extends OSUtil {
		@Override
		public File getUserHomeDirectory() {
			return new File(System.getProperty("user.home")); 
		}

		@Override
		public void changeWallpaper(String path) {
			User32Lib.INSTANCE.SystemParametersInfo(
			          new UINT_PTR(User32Lib.SPI_SETDESKWALLPAPER), 
			          new UINT_PTR(0), 
			          path, 
			          new UINT_PTR(User32Lib.SPIF_UPDATEINIFILE | User32Lib.SPIF_SENDWININICHANGE));			
		}			
		
		private interface User32Lib extends StdCallLibrary {
		      long SPI_SETDESKWALLPAPER = 20;
		      long SPIF_UPDATEINIFILE = 0x01;
		      long SPIF_SENDWININICHANGE = 0x02;

		      User32Lib INSTANCE = (User32Lib) Native.loadLibrary("user32", User32Lib.class, new HashMap<Object, Object>() {
				private static final long serialVersionUID = -5782999231858533058L;
				{
		            put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
		            put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
		         }
		      });

		      boolean SystemParametersInfo(
		          UINT_PTR uiAction,
		          UINT_PTR uiParam,
		          String pvParam,
		          UINT_PTR fWinIni
		      );
		  }
	}
	
	private static class LinuxGNOMEUtil extends OSUtil {
		@Override
		public File getUserHomeDirectory() {
			return new File(System.getenv("HOME"));
		}

		@Override
		public void changeWallpaper(String path) {
			String command = "gsettings set org.gnome.desktop.background picture-uri file:///" + path; 
			try {
				Runtime.getRuntime().exec(command);
			} catch (IOException e) {
				throw new WPPException(e);
			}			
		}		
	}	

}
